import api from '@h5app/sheep/api'
import { CreateTimeFilter, FollowTimeFilter } from '@h5app/sheep/interface/dictionaries'
import { DictionaryEnum } from '@h5app/sheep/interface/enum'
import type { Dictionary as DictionaryType } from '@h5app/sheep/interface/type/Dictionary'
import { acceptHMRUpdate, defineStore } from 'pinia'
import { ref } from 'vue'

let isInit = false
export const useDictionariesStore = defineStore('dictionaries', () => {
  const dictionaries = ref<Record<DictionaryEnum, DictionaryType[]>>()

  const getDictionaries = (key: DictionaryEnum) => {
    if (!dictionaries.value) init()
    return dictionaries.value?.[key] || []
  }

  const init = async () => {
    if (isInit) return
    isInit = true

    const values = Object.values(DictionaryEnum)
    const dictionariesIdList =
      Object.values(DictionaryEnum)
        .splice(values?.length * 0.5)
        .map((key) => Number(key)) || []
    const { data } = await api.dictionaries(dictionariesIdList)
    if (!data) return
    const temp: any = {}
    dictionariesIdList.forEach((key) => {
      temp[key] =
        data[key]?.map?.((item: any) => ({
          label: item.dataVal,
          value: item.dataId,
          key: item.dicTypeId,
        })) || []
    })

    temp[DictionaryEnum.跟进时间] = FollowTimeFilter
    temp[DictionaryEnum.创建时间] = CreateTimeFilter

    temp[DictionaryEnum.是否] = [
      {
        label: '是',
        value: 0,
        key: 0,
      },
      {
        label: '否',
        value: 1,
        key: 1,
      },
    ]

    temp[DictionaryEnum.有无] = [
      {
        label: '有',
        value: 0,
        key: 0,
      },
      {
        label: '无',
        value: 1,
        key: 1,
      },
    ]

    dictionaries.value = temp
  }

  return { init, dictionaries, getDictionaries }
})
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useDictionariesStore, import.meta.hot))
}
